package traditional.thread.communicate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 改动点1：将原来2个线程相互激活的，改成3个线程 改动点2：循环应该放在创建线程的内部。否则每循环一次就创建一个线程，太浪费了
 * 
 * @author Germmy
 *
 */
public class TheadLockTestZxxWithCommunicate {

	public static void main(String[] args) {

		final Business business = new Business();

		// 整体循环50次

		new Thread(new Runnable() {

			public void run() {
				for (int i = 0; i < 50; i++) {
					// 大哥来搞100次
					business.main(i);
				}

			}
		}).start();

		new Thread(new Runnable() {

			public void run() {
				for (int i = 0; i < 50; i++) {
					// 小弟来搞10次
					business.sub(i);
				}
			}
		}).start();

	}

	static class Business {
		boolean isShouldSub = true;
		Lock lock = new ReentrantLock();
		Condition condition = lock.newCondition();

		void main(int ii) {
			lock.lock();
			try {
				while (isShouldSub) {
					try {
						condition.await();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for (int i = 0; i < 100; i++) {
					System.out.println("main:" + i);
				}
				isShouldSub = true;
				condition.signal();
			} finally {
				lock.unlock();
			}
		}

		void sub(int ii) {
			lock.lock();
			try {
				while (!isShouldSub) {
					try {
						condition.await();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for (int i = 0; i < 10; i++) {
					System.out.println("sub:" + i);
				}
				isShouldSub = false;
				condition.signal();
			} finally {
				lock.unlock();
			}
		}

	}

}
